<?php
/*
 * Created on 2014-1-19
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
 
 
  set_time_limit(0);
 header('Content-Type:text/html;charset=utf-8');
  ini_set('display_errors',0);
 if ($_GET['debug']==1){
 	ini_set('display_errors',1);
 }
 include '../../../nn_logic/nl_common.func.php';
 $db = nl_get_db(NL_DB_WRITE);
 if (!$db->open())
  echo '打开数据库错误！';
  
 if ($_GET['export']==1){
 	$path='/data/export_csv/';
 	$file_path=dirname(dirname(dirname(dirname(__FILE__)))).$path;
 	@mkdir($file_path, 0777, true);
 	$file_name=date('YmdHis').'.csv';
 	$file_path .= $file_name;
 	__create_svc($file_path);
 	$bool=true;
 	while($bool){
 		$re=__check_vod_online($db);
 		if ($re['over']){
 			$bool=false;
 		}else{
 			$_REQUEST['bench']=$re['bench'];
 		}
 		
 		__write_to_svc($re['data'],$file_path);
 		$re=null;
 	}
 	
 	header("Content-Type: application/octet-stream;charset=utf-8");
 	header("Content-Disposition:attachment;filename=" . $file_name);
 	
 	@readfile($file_path);
// 	 $fp = @fopen( $file_path, "r" );
//       @fpassthru( $fp );
//                @fclose( $fp );
 	
 	@unlink($file_path);
 	die;
 }elseif ($_POST['lock']==1){
 	$video_id=$_POST['nns_video_id'];
 	$re=__lock($db,$video_id);
 	if ($re===TRUE){
 		echo json_encode(array('code'=>0,'reason'=>'OK','id'=>$video_id));
 	}else{
 		echo json_encode(array('code'=>1,'reason'=>'FAIL,DB ERROR','id'=>$video_id));
 	}
 	die;
 }elseif ($_POST['unline']==1){
 	$video_id=$_POST['nns_video_id'];
 	$re=__unline($db,$video_id);
 	if ($re===TRUE){
 		echo json_encode(array('code'=>0,'reason'=>'OK','id'=>$video_id));
 	}else{
 		echo json_encode(array('code'=>1,'reason'=>'FAIL,DB ERROR','id'=>$video_id));
 	}
 	die;
 }elseif ($_POST['lock']==-1){
 	$video_id=$_POST['nns_video_id'];
 	$re=__lock($db,$video_id,1);
 	if ($re===TRUE){
 		echo json_encode(array('code'=>0,'reason'=>'OK','id'=>$video_id));
 	}else{
 		echo json_encode(array('code'=>1,'reason'=>'FAIL,DB ERROR','id'=>$video_id));
 	}
 	die;
 } else{
 	echo json_encode(__check_vod_online($db));
 }
 
 function __lock($db,$video_id,$lock=0){
 	//$lock_sql = "update nns_assists_item set nns_check='{$lock}' WHERE nns_video_id='$video_id'"; 
    //$re = nl_execute_by_db($lock_sql, $db);
    //return $re;
 }
 
 function __unline($db,$video_id){
 	//$lock_sql = "delete from  nns_assists_item  WHERE nns_video_id='$video_id'"; 
    //$re = nl_execute_by_db($lock_sql, $db);
    //return $re;
 }
  
 function __create_svc($file_path){
 	$fp = fopen($file_path, 'w+');
 	fwrite($fp, "\xEF\xBB\xBF"); // utf-8 bom

	$line = array(
		'影片ID',
		'影片名称',
		'状态',
		'描述',
		'存在问题的分集',
		'创建时间',
		'注入类型',
		'注入ID'
		);
	fputcsv($fp, $line);
 	
 }
  
 function __write_to_svc($list,$file_path){
 	
		$fp = fopen($file_path, 'a');
		
		foreach ($list as $search_item) {
			if(strlen($search_item["indexs"])==0){
				continue;
			}
			if($search_item["type"]=='other'){
				continue;
			}
			$line = array(
			$search_item["nns_id"],
			$search_item["nns_name"],
			$search_item["nns_check"],
			$search_item["type"],
			"{$search_item["indexs"]}",
			$search_item["nns_create_time"],
			$search_item["nns_import_source"],
			$search_item["nns_asset_import_id"]
			
			);
		    fputcsv($fp,$line);
		    
		}

		fclose($fp);
 }
 
//  var_dump(__check_media_perfect($db,'330f04dce0372eabdeaad787fad8eb60'));
 function __check_vod_online($db){
 	$num=100;
 	$total=0;
 	$ups=0;
 	$bool=true;
 	
 	$since=$_REQUEST['bench'];
 	$btime=$_REQUEST['btime'];
 	$etime=$_REQUEST['etime'];
 	$search=$_REQUEST['search'];
 	$category=$_REQUEST['category'];
 	$type=$_REQUEST['type'];
 	$online=$_REQUEST['online'];
 	$total=$_REQUEST['total'];
 	$update=$_REQUEST['update'];
 	
 	$ex_sql='';
 	if (strlen($category)>0){
 		$category=explode(',',$category);
 		$ex_sql .=" and nns_depot_id='{$category[0]}' and nns_category_id like '{$category[1]}%' ";
 	}
 	
 	if (strlen($search)>0){
 		$ex_sql .= " and  (nns_name like '%{$search}%' or nns_pinyin like '%{$search}%' or nns_id ='{$search}' ) ";	
 	}
 	
 	$since=empty($since)?0:(int)$since;
 	$total=empty($total)?0:(int)$total;
 	
 	$etime= date('Y-m-d',strtotime($etime)).' 23:59:59';
 	if (strlen($btime)>0 && strlen($etime)>0){
 		$ex_sql .= " and nns_create_time >= '{$btime}' and nns_create_time <= '{$etime}' ";	
 	}
 	
 	$sql="select nns_asset_import_id,nns_import_source,nns_id,nns_name,nns_create_time from nns_vod   where     nns_deleted!=1  {$ex_sql}  limit $since,$num ";
 	 	
 	 	$arr = nl_query_by_db($sql,$db);
 	 	if (is_bool($arr)) $bool=false;
 	 	if (count($arr) < $num){
 	 		$bool=false;
 	 	}
 	 	
 	 	$result=array();
 	 	
 	 	foreach ($arr as $item ){
 	 		$item['nns_check'] =1;
 	 		if (strlen($item['nns_check'])>0 ){
 	 			if ($item['nns_check']=='0'){
 	 				$item['nns_check']='lock';
 	 			}else{
 	 				$item['nns_check']='online';
 	 			}
 	 		}else{
 	 			$item['nns_check']='offline';
 	 		}
 	 		
 	 		//if ($online!=$item['nns_check'] && !empty($online)) continue;
 	 		
 	 		$is_up=__check_media_perfect($db,$item['nns_id']);
 	 		
 	 		if (strlen($update)>0 && !is_array($is_up)){
 	 			continue;
 	 		}
 	 		
 	 		
 	 		if ($is_up===1){
 	 			if ($online=='online' || empty($online)) continue;
 	 			if ($type=='other' || empty($type) ){
 	 				$total++;
 	 				$item['type']='other';
 	 				$item['indexs']='--';
 	 				array_push($result,$item);
 	 			}
// 	 			echo $item['nns_id']."   ".$item['nns_name']."<br>";
 	 		}if (is_array($is_up)){
 	 			
 	 			if (strlen($update)>0 && $is_up['type']!='media'){
 	 				continue;
 	 			}
 	 			
 	 			if ($is_up['type']=='index'){
// 	 				$indexs=implode(',',$is_up['data']);
					$indexs=$is_up['data'];
 	 				if ($type=='index' || empty($type)){
	 	 				$total++;
	 	 				$item['type']='index';
	 	 				$item['indexs']=$indexs;
	 	 				array_push($result,$item);
 	 				}
// 	 				echo "<font color='#0099cc'>".$item['nns_id']."   ".$item['nns_name']."</font>  【".$indexs."】缺分集<br>";
 	 			}elseif ($is_up['type']=='media'){
// 	 				$indexs=implode(',',$is_up['data']);
					$indexs=$is_up['data'];
 	 				if ($type=='media' || empty($type)){
	 	 				
	 	 				$item['type']='media';
	 	 				$item['indexs']=$indexs;
	 	 				$item['update']=$is_up['update'];
	 	 				
	 	 				if (strlen($update)>0 && $item['update']==$update){
	 	 					$total++;
	 	 					array_push($result,$item);
	 	 				}elseif (strlen($update)==0){
	 	 					$total++;
	 	 					array_push($result,$item);
	 	 				}	 	 				
 	 				}
 	 			}
 	 		}elseif($is_up===0){
 	 			if ($type=='index' || empty($type)){
	 	 				$total++;
	 	 				$item['type']='index';
	 	 				$item['indexs']='all';
	 	 				array_push($result,$item);
 	 			}
 	 		}
 	 	} 	 	
 	 	$arr=null; 	
 		$rbench=$since+$num;
 		$re=array();
 		$re['bench']=$rbench;
 		$re['total']=$total;
 		$re['over']=!$bool;
 		$re['data']=$result;
 		return $re;
 	 
 }
 
 
  function __check_media_perfect($db, $vod_id) {
//		如果未开启检查完整片源 则返回
        $up = 1;//上线
        $down = 0;//下线
//		是否分集总数-1与最大分集数相等,若是，则上线，否则下线
        $index_sql = "SELECT MAX(`nns_index`) AS max , MIN(`nns_index`) AS min, count(1) as count,nns_index FROM `nns_vod_index` WHERE nns_vod_id='$vod_id'  and nns_deleted!=1 "; //查询最大分集和最小分集
        
        $index_info = nl_query_by_db($index_sql, $db);
       
        $index_info = $index_info[0];
		
		
		
		
		
         if ($index_info['count']==0)
            return $down;
        $index_num = $index_info['max'] - $index_info['min'] + 1; //总分集+1为总集数
        //var_dump($index_num);
		if($index_info['count']>$index_num){
			$index_info['count']=$index_num;
		}
        if ($index_num != $index_info['count']){
        	$indexs='';
        	$index_sql_1 = "SELECT nns_index FROM `nns_vod_index` WHERE nns_vod_id='$vod_id'  and nns_deleted!=1  order by nns_index"; //查询最大分集和最小分集
        	$indexs_1 = nl_query_by_db($index_sql_1, $db);
//        	var_dump($indexs_1);die;
			if ($index_num-count($indexs_1)>200){
				$indexs = '缺集超过200集';
			}else{
				$indexs_1=np_array_rekey($indexs_1,'nns_index');
	        	for($i=$index_info['min'];$i<=$index_info['max'];$i++){
	        		if (empty($indexs_1[$i])){
	//        			array_push($indexs,$i);
						$indexs .=((int)$i+1).',';
	        		}
	        	}
			}
        	return array(
        		'type'=>'index',
        		'data'=>rtrim($indexs,',')
        	);
        }
            
        $media_sql = "SELECT nns_index FROM nns_vod_index WHERE nns_id NOT IN(SELECT nns_vod_index_id FROM nns_vod_media WHERE nns_vod_id='$vod_id'  and nns_vod_media.nns_deleted!=1) AND nns_vod_id='$vod_id'  and  nns_vod_index.nns_deleted!=1   order by nns_index ";
        $media_count = nl_query_by_db($media_sql, $db);
        if ($media_count == false || is_array($media_count) ){
//        	$medias=array();
			$media_count=np_array_rekey($media_count,'nns_index');
			$medias='';
			if (count($media_count)>200){
				$medias = '缺片源超过200集';
			}else{
				$j=0;
				$update=0;
				for ($n=$index_info['max'];$n>=$index_info['min'];$n--){
//	        	foreach ($media_count as $n=>$v){
	        		if (!isset($media_count[$n])){
			 			$j=$n;
			 		}elseif (isset($media_count[$n])){
			 			$medias = ((int)$n+1).','.$medias;
			 			if ( $j>=$n){
			 				$update=1;
			 			}
			 		} 
	//        		array_push($medias,$v['nns_index']);
					
	        	}
			}
        	return array(
        		'type'=>'media',
        		'data'=>rtrim($medias,','),
        		'update'=>$update
        	);
//        	return $media_count;
        } //每个分集都有片源
            
        return  $up; //上线
    }
?>
